package ch.bfh.fbi.mobicomp.zap06;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import ch.simplix.android.speech.string.FrenchString;
import ch.simplix.android.speech.string.GermanString;
import ch.simplix.android.speech.string.UKString;
/**
 * Zap05 seemed to work until we tried to abort the count down. This is due to the IntentService, where a seperate working thread does take the work from a worker queue. 
 * This queue serializes the work so each service-call is executed in sequence.
 * 
 * Zap06 uses a normal Service again, but the needed thread-handling is done 'by hand'.
 * Now the application runs as requested on the emulator.
 * 
 * @author reto
 *
 */
public class Zap06Service extends Service {
	
	private static final String TAG = "Zap06Service";

	private Thread thread;

	@Override
	public IBinder onBind(Intent intent) {
		// We do not want to grand explicite access!
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent.getExtras().getBoolean("start")) {
			Log.d(TAG, "destruction initiated...");
			if (thread == null || !thread.isAlive()) {
				initiateAutoDestruction();
			}
		} else if (intent.getExtras().getBoolean("stop")) {
			Log.d(TAG, "destruction aborted...");

			resetAutoDestruction();

		} else {
			Log.d(TAG, "unknown command.");
		}

		return super.onStartCommand(intent, flags, startId);
	}

	private Intent speechIntent = new Intent(
			"ch.simplix.android.speech.SPEECH_SERVICE");
	private long countdown;

	private void resetAutoDestruction() {
		if (countdown == 0)
			return;
		try {
			thread.interrupt();
			thread=null;
			countdown = 0;
		} catch (Exception ex) {
			// if there is no thread.
		}

		speechIntent.putExtra("Phrase", new UKString(
				"Self destruction sequence aborted."));
		startService(speechIntent);
		speechIntent.putExtra("Phrase", new GermanString(
				"Selbstzerstörungssequenz abgebrochen."));
		startService(speechIntent);
		speechIntent.putExtra("Phrase", new FrenchString(
				"Séquence d'autodestruction avortée."));
		startService(speechIntent);

	}

	private void initiateAutoDestruction() {
		if (countdown != 0)
			return;
		countdown = System.currentTimeMillis() + 3 * 60 * 1000;
		speechIntent.putExtra("Phrase", new UKString(
				"Self destruction sequence initiated."));
		startService(speechIntent);
		speechIntent.putExtra("Phrase", new GermanString(
				"Selbstzerstörungs Sequenz eingeleitet."));
		startService(speechIntent);
		speechIntent.putExtra("Phrase", new FrenchString(
				"Séquence d'autodestruction declanchée."));
		startService(speechIntent);
		thread = new Thread() {
			public void run() {
				countDown();
			}
		};
		thread.start();
	}

	private void countDown() {
		try {
			int timeLeft = (int) ((countdown - System.currentTimeMillis()) / 1000);
			while (timeLeft > 70) {
				minutesCount(timeLeft);
				Thread.sleep(60000); // 1 Minute
				timeLeft = (int) ((countdown - System.currentTimeMillis()) / 1000);
			}
			while (timeLeft > 11) {
				secondsBlockCount(timeLeft);
				Thread.sleep(10000); // 10 Seconds
				timeLeft = (int) ((countdown - System.currentTimeMillis()) / 1000);
			}
			while (timeLeft > 0) {
				secondsCount(timeLeft);
				Thread.sleep(1000); // 1 Second
				timeLeft = (int) ((countdown - System.currentTimeMillis()) / 1000);
			}
			destroy();
		} catch (InterruptedException ex) {
		}
	}

	private void minutesCount(int timeLeft) {
		speechIntent.putExtra("Phrase", new UKString(""
				+ (1 + (timeLeft / (60))) + "Minutes until self destruction"));
		startService(speechIntent);
		speechIntent
				.putExtra("Phrase", new GermanString(""
						+ (1 + (timeLeft / (60)))
						+ "Minuten bis zur Selbstzerstörung"));
		startService(speechIntent);
		speechIntent.putExtra("Phrase", new FrenchString(""
				+ (1 + (timeLeft / (60)))
				+ "minutes jusqu'à ce que l'auto-destruction"));
		startService(speechIntent);
	}

	private void secondsBlockCount(int timeLeft) {
		if (timeLeft % 3 == 0) {
			speechIntent.putExtra("Phrase", new UKString(""
					+ (10 + (timeLeft / 10 * 10))
					+ "Seconds until self destruction"));
		} else if (timeLeft % 3 == 1) {
			speechIntent.putExtra("Phrase", new GermanString(""
					+ (10 + (timeLeft / 10 * 10))
					+ "Sekunden bis zur Selbstzerstörung"));
		} else {
			speechIntent.putExtra("Phrase", new FrenchString(""
					+ (10 + (timeLeft / 10 * 10))
					+ "seconds jusqu'à ce que l'auto-destruction"));
		}
		startService(speechIntent);
	}

	private void secondsCount(int timeLeft) {
		speechIntent.putExtra("Phrase", new UKString("" + (timeLeft)));
		startService(speechIntent);
	}

	private void destroy() {
		countdown = 0;
		speechIntent.putExtra("Phrase", new UKString("Self destroying now."));
		startService(speechIntent);
	}
}
